from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin


class SimpleMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        origin = request.headers.get('Origin')
        response["Access-Control-Allow-Origin"] = origin
        return response


# “预检”请求时，允许请求方式则需服务器设置响应头：Access-Control-Request-Method
# “预检”请求时，允许请求头则需服务器设置响应头：Access-Control-Request-Headers

class ComplexMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.method == 'OPTIONS':
            # 处理预检请求
            response = HttpResponse()
            response["Access-Control-Allow-Methods"] = "OPTIONS,GET"
            response["Access-Control-Allow-Headers"] = "*"
            return response
        return None

    def process_response(self, request, response):
        response["Access-Control-Allow-Origin"] = '*'
        return response
